from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from alipay import AliPay
from django.conf import settings
import os
from rest_framework.permissions import IsAuthenticated

from orders.models import OrderInfo
from .models import Payment
# Create your views here.


# GET /orders/(?P<order_id>\d+)/payment/
class PaymentView(APIView):
    """支付宝支付"""

    # 用户权限校验
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        """获取支付页面"""
        # 验证order_id
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=request.user, pay_method=OrderInfo.PAY_METHODS_ENUM["ALIPAY"],
                                          status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"])
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单异常'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建对接支付宝的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 调用对接支付宝的支付接口
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url="http://www.meiduo.site:8080/pay_success.html",
        )

        # 正式环境：电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        # 测试环境：电脑网站支付，需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string
        # 响应alipay_url
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return Response({'alipay_url': alipay_url})


#  PUT /payment/status/?支付宝参数
class PaymentStatusView(APIView):
    """修改订单的状态"""
    # charset=utf-8&out_trade_no=20180711011212000000010
    # &method=alipay.trade.page.pay.return&total_amount=3398.00
    # &sign=IBrmEkLQY8VfjoDSNbzHIgiSD1nsZfphkPydaq07nN3sMOc4XqcVU3t67VKtQPHgrrfjyyj6wvlkaye8TABdn1LCjYxh%2B%2FfkMATAraNfzPRN1%2FG77pcyf%2BWPesHNKrkl%2FRetKM1bGkrJGW4ORLsyRExyE8LBf02SaoxfypuFhwL1mvQ1iDPaszM4DPWK7YOKgvKQTPfWqmIl2oFiDdVODeHzPdLa9Gslq89SsxhuQ4whpP6mohmKCtGYgQ%2F6iDCTKGCBFiN1COuPMnGY638ee8Zce1hT18ILjQ2X82AOtQMhecJ0%2FvKzhp4ByAXyac5DFKfNwMU7W0yzaAUXKKhI2g%3D%3D
    # &trade_no=2018071121001004300200474268
    # &auth_app_id=2016091800541436&version=1.0
    # &app_id=2016091800541436&sign_type=RSA2&seller_id=2088102176212592&timestamp=2018-07-11+09%3A13%3A19
    def put(self, request):
        # 读取查询字符串
        query_dict = request.query_params
        # 将QueryDict类型强转为python字典类型
        data = query_dict.dict()
        # 剔除并获取支付宝签名信息
        signature = data.pop('sign')

        # 创建对接支付宝的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 使用data进行RSA2计算,和signature进行比较,如果为True则表示支付成功
        success = alipay.verify(data, signature)

        if success:
            # 从请求参数中获取订单号以及支付宝维护的交易流水号
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')

            # 记录支付宝维护的交易流水号
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 修改订单状态为待发货
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])

            # 返回响应:JSON
            return Response({'trade_id': trade_id})

        else:
            return Response({'message': '非法请求'}, status=status.HTTP_403_FORBIDDEN)
